package com.example.lottery.common.utils;


import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {
    private JacksonUtil() {

    }

    private static final ObjectMapper objectMapper = new ObjectMapper();

    //封装异常
    private static final <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JacksonException.class);
    }

    //从标准库中抄的异常
    private static final <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return (T)parser.call();
        } catch (Exception ex) {
            if (check.isAssignableFrom(ex.getClass())) {
                throw new JsonParseException(ex);
            }
            throw new IllegalStateException(ex);
        }
    }


    //序列化方法
    public static String writeValueAsString(Object object) {
        return JacksonUtil.tryParse(() -> {
            return objectMapper.writeValueAsString(object);
        });
    }


    //反序列化方法
    public static <T> T readValue(String str,Class<T> valueType) {
        return JacksonUtil.tryParse(()-> {
           return objectMapper.readValue(str, valueType);
        });
    }

    //List的反序列化

    public static <T> T readListValue(String str,Class<?> paramClass) {
        JavaType javaType = objectMapper.getTypeFactory()
                .constructParametricType(List.class, paramClass);

        return JacksonUtil.tryParse(()->{
            return objectMapper.readValue(str, javaType);
        });
    }

    //todo Map的反序列化

}
